<?php

namespace App\Http\Controllers\Api;

use App\Models\Member;
use App\Models\MemberFollow;
use Illuminate\Http\Request;

class MemberFollowController extends Controller
{
    public function followList(Request $request)
    {
        $memberId = $request->input('member_id');
        if (!$memberId) return $this->error('会员ID不能为空');

        $list = MemberFollow::select(['follow_id', 'created_at'])
            ->with(['follow_member' => function ($q) {
                $q->select(['id', 'nickname', 'avatar', 'sign']);
            }])->whereHas('follow_member')->where('member_id', $memberId)->orderByDesc('id')->paginate();

        if (auth('api')->check()) {
            $followMemberIds = MemberFollow::where('member_id', auth('api')->user()->id)->pluck('follow_id')->all();
        }

        foreach ($list as $item) {
            $item->is_follow = in_array($item->follow_id, $followMemberIds ?? []);
        }

        if (auth('api')->check()) {
            $isSelf = auth('api')->user()->id == $memberId;
        }

        return $this->_success(['list' => $list->items(), 'is_self' => $isSelf ?? false, 'total' => $list->total()]);
    }

    public function follow(Request $request)
    {
        $followId = $request->input('follow_id');
        if (!$followId) return $this->error('会员ID不能为空');

        $exists = Member::where('id', $followId)->exists();
        if (!$exists) return $this->error('会员不存在');

        $memberId = auth('api')->user()->id;
        if ($followId == $memberId) return $this->error('不能关注自己');

        $record = MemberFollow::where(['member_id' => $memberId, 'follow_id' => $followId])->first();

        if ($record) {
            $record->delete();
            return $this->success('取消关注成功');
        }

        MemberFollow::create(['member_id' => $memberId, 'follow_id' => $followId]);

        return $this->success('关注成功');
    }

    public function fans(Request $request)
    {
        $memberId = $request->input('member_id');
        if (!$memberId) return $this->error('会员ID不能为空');

        if (auth('api')->check()) {
            $followMemberIds = MemberFollow::where('member_id', auth('api')->user()->id)->pluck('follow_id')->all();
        }

        $list = MemberFollow::select(['member_id', 'created_at'])->with(['member' => function ($q) {
            $q->select(['id', 'nickname', 'avatar', 'sign']);
        }])->whereHas('member')->where('follow_id', $memberId)->orderByDesc('id')->paginate();

        foreach ($list as $item) {
            $item->is_follow = in_array($item->member_id, $followMemberIds ?? []);
        }

        if (auth('api')->check()) {
            $isSelf = auth('api')->user()->id == $memberId;
        }

        return $this->_success(['list' => $list->items(), 'is_self' => $isSelf ?? false, 'total' => $list->total()]);
    }
}
